package com.yunxin.admin.system.infra.persistence.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxin.admin.system.domain.model.dept.Dept;
import com.yunxin.admin.system.domain.model.dept.DeptRepository;
import com.yunxin.admin.system.infra.persistence.converter.DeptConverter;
import com.yunxin.admin.system.infra.persistence.entity.SysDeptDO;
import com.yunxin.admin.system.infra.persistence.mapper.SysDeptMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

/**
 * @author zero°
 * @since 2023-07-11
 */
@Repository
@RequiredArgsConstructor
public class DeptRepositoryImpl extends ServiceImpl<SysDeptMapper, SysDeptDO> implements DeptRepository, IService<SysDeptDO> {

    private final DeptConverter deptConverter;

    @Override
    public boolean saveDept(Dept dept) {
        SysDeptDO sysDeptDO = deptConverter.formDept(dept);
        boolean result = this.save(sysDeptDO);
        dept.setId(sysDeptDO.getId());
        return result;
    }

    @Override
    public boolean updateDept(Dept dept) {
        SysDeptDO sysDeptDO = deptConverter.formDept(dept);
        return this.updateById(sysDeptDO);
    }

    @Override
    public boolean remove(Long id) {
        return this.remove(new LambdaQueryWrapper<SysDeptDO>().eq(SysDeptDO::getId, id).or()
                .apply("CONCAT (',',tree_path,',') LIKE CONCAT('%,',{0},',%')", id));
    }

    @Override
    public Dept getDeptById(Long id) {
        SysDeptDO sysDeptDO = this.getById(id);
        return deptConverter.toDept(sysDeptDO);
    }
}
